import React from 'react';
import {injectIntl, language} from './intl';
import {Table, Form, Row, Col, Modal, Alert} from 'antd';
import PropTypes from 'prop-types';
import {
    PAGE,
    TABLE,
    PAGINATION_OPTIONS,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    FIXED_COLUMN_WIDTH,
    DATETIME_FORMAT,
    FORM_OPTIONS,
    FORM_ROW_OPTIONS,
} from '../constants';
import styles from './style.css';
import {hasPermissions, conventSorter} from './utils';
import {baseDataStatus, orderUnmetReasonType} from '../Enum';
import {conventEnumValueToString, formatDateTime} from '../utils';
import {PERMISSION} from './constants';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {updateInfo} from './api';
import TextInput from 'Shared/components/TextInput';

const autosize = {minRows: 1};
import WrappedSelect from '../common/WrappedSelect';
const FormItem = Form.Item;
export class TablePanel extends React.PureComponent {
    state = {
        loading: false,
        showPanel: false,
        isValidate: false,
        name: '',
        remark: '',
        currentId: '',
    }

    showPanel = () => {
        this.setState({
            showPanel: !this.state.showPanel
        });
    }
    handleFilterChange = (value, name) => {
        this.setState({
            [name]: value
        });
    }

    handleAbandon = id => {
        this.setState({
            loading: true
        });
        this.props.onClickAbandon(id).then(() => {
            this.setState({
                loading: false
            });
        });
    }

    onClickEdit = e => {
        const {id} = e.target.dataset;
        const {code, name, type, remark} = this.props.data.find(item => item.id === id);
        this.setState({
            code,
            name,
            type,
            remark,
            currentId: id,
            showPanel: true
        });
    }

    onCancel = () => {
        this.setState({
            code: '',
            name: '',
            remark: '',
            type: undefined,
            currentId: '',
            isValidate: false,
            showPanel: false
        });
    }
    onSubmit = () => {
        const {name, type, remark, currentId} = this.state;
        if(!currentId) return;
        if(!name || !type)
            return this.setState({
                isValidate: true,
            });
        this.setState({
            loading: true
        });
        const {rowVersion} = this.props.data.find(item => item.id === currentId) || {};
        return updateInfo(currentId, {
            name,
            type,
            remark,
            rowVersion
        }).then(res => {
            this.setState({
                loading: false,
            });
            if(res.ok) {
                this.onCancel();
                this.props.querySearch();
            }
        });
    }
    onChangeSort = (pagination, filters, sorter) => {
        if(pagination.current - 1 === this.props.pageIndex && pagination.pageSize === this.props.pageSize)
            this.props.onChangeSort({
                ...conventSorter(sorter),
                pageIndex: PAGE.index
            });
    };

    render() {
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.code',
                    defaultMessage: '编号'
                }),
                dataIndex: 'code',
                sorter: true,
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.name',
                    defaultMessage: '名称'
                }),
                dataIndex: 'name'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.brand',
                    defaultMessage: '品牌'
                }),
                dataIndex: 'brand',
                render: (text, record) => `(${record.brandCode})${record.brandName}`
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.type',
                    defaultMessage: '类型'
                }),
                sorter: true,
                dataIndex: 'type',
                render: text => conventEnumValueToString(orderUnmetReasonType, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                render: text => conventEnumValueToString(baseDataStatus, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.createTime',
                    defaultMessage: '创建时间'
                }),
                dataIndex: 'createTime',
                sorter: true,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.action',
                    defaultMessage: '操作'
                }),
                dataIndex: 'action',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (t, r) => {
                    const menus = [
                        {
                            id: PERMISSION.update,
                            children: (
                                <a key="update" onClick={this.onClickEdit} data-id={r.id}>
                                    {this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.update',
                                        defaultMessage: '编辑'
                                    })}
                                </a>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update))
                        },
                        {
                            id: PERMISSION.abandon,
                            children: ref =>
                                <WrappedPopconfirm
                                    id={r.id}
                                    key="abandon"
                                    title={this.props.intl.formatMessage({
                                        id: 'tablePanel.popconfirm.message',
                                        defaultMessage: '是否继续?'
                                    })}
                                    onVisibleChange={ref.setMenuVisible}
                                    onConfirm={this.handleAbandon}>
                                    <a key="abandon">
                                        {this.props.intl.formatMessage({
                                            id: 'tablePanel.operation.abandon',
                                            defaultMessage: '作废'
                                        })}
                                    </a>
                                </WrappedPopconfirm>,
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon))
                        },
                    ];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            }
        ];
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            onShowSizeChange: this.props.onPageSizeChange,
            onChange: this.props.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const msgs = [];
        if(!this.state.name)
            msgs.push(this.props.intl.formatMessage({
                id: 'tablePanel.alert.name',
                defaultMessage: '名称'
            }));
        if(!this.state.type)
            msgs.push(this.props.intl.formatMessage({
                id: 'tablePanel.alert.type',
                defaultMessage: '类型'
            }));
        const alertMessage = msgs.length ? `${msgs.join(
            this.props.intl.formatMessage({
                id: 'tablePanel.comma',
                defaultMessage: '、'
            })
        )}${this.props.intl.formatMessage({
            id: 'tablePanel.notEmpty',
            defaultMessage: '不能为空'
        })}` : '';
        return (
            <div>
                <Modal
                    title={this.props.intl.formatMessage({
                        id: 'tablePanel.modale.title',
                        defaultMessage: '编辑'
                    })}
                    width="60%"
                    maskClosable={false}
                    onOk={this.onSubmit}
                    destroyOnClose={true}
                    confirmLoading={this.state.loading}
                    visible={this.state.showPanel}
                    onCancel={this.onCancel}>
                    <Form className="form-standard">
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    validateStatus={this.state.isValidate && !this.state.name ? 'error' : null}
                                    required
                                    label={this.props.intl.formatMessage({
                                        id: 'tablePanel.form.name',
                                        defaultMessage: '名称'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <TextInput name="name"
                                        value={this.state.name} onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'tablePanel.form.type',
                                        defaultMessage: '类型'
                                    })}
                                    {...FORM_OPTIONS.item}
                                    validateStatus={this.state.isValidate && !this.state.type ? 'error' : null}
                                    required>
                                    <WrappedSelect
                                        name="type"
                                        value={this.state.type}
                                        options={orderUnmetReasonType.toList(language)}
                                        onChange={this.handleFilterChange} />
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'tablePanel.form.remark',
                                    defaultMessage: '备注'
                                })}
                                {...FORM_ROW_OPTIONS.item}>
                                <TextInput type="textarea" name="remark" autosize={autosize}
                                    value={this.state.remark} onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Row>
                        {this.state.isValidate && alertMessage && <Alert message={alertMessage} className={styles.alertMargin} type="warning" showIcon />}
                    </Form>
                </Modal>
                <Table
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={this.props.data}
                    rowKey="id"
                    pagination={pagination}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    locale={locale}
                    {...TABLE} />
            </div>
        );
    }
}
TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    errorMessage: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    onClickAbandon: PropTypes.func.isRequired,
    onPageIndexChange: PropTypes.func.isRequired,
    onPageSizeChange: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch, onClickAbandon} from './actions';
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    permissions: getPermissions(state)
});

const mapDispatchToProps = dispatch => ({
    onPageSizeChange: (pageIndex, pageSize) =>
        dispatch(
            tableSearch({
                pageIndex: PAGE.index,
                pageSize
            })
        ),
    onPageIndexChange: pageIndex =>
        dispatch(
            tableSearch({
                pageIndex: pageIndex - 1
            })
        ),
    onChangeSort: option => dispatch(tableSearch(option)),
    onClickAbandon: id =>
        dispatch(onClickAbandon(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    querySearch: () => {
        dispatch(tableSearch());
    }
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(TablePanel));
